//
//  YZBaseVC.swift
//  ZYA
//
//  Created by 邱仙凯 on 2024/12/12.
//  Copyright © 2024 zwb. All rights reserved.
//

import UIKit

class YZBaseVC: UIViewController {
    lazy var topCollection: UICollectionView = {
        let  v = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout1)
        v.backgroundColor =  Theme.pureWhite()
        v.register(BoarSuperCollCell.self, forCellWithReuseIdentifier: BoarSuperCollCell.identifier)
        v.contentInset = UIEdgeInsets(top: 0, left: 10, bottom:  0, right: 10)
        return v
    }()
    
    
    lazy var bottomCollection: UICollectionView = {
        let v = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout2)
        v.backgroundColor =  Theme.pureWhite()
        v.register(BoarSuperCollCell.self, forCellWithReuseIdentifier: BoarSuperCollCell.identifier)
        v.contentInset = UIEdgeInsets(top: 0, left: 10, bottom:  0, right: 10)
        return v
    }()
    lazy var layout1:UICollectionViewFlowLayout = {
        let layout = UICollectionViewFlowLayout()
        layout.footerReferenceSize = CGSize(width: 0,height: 0)
        layout.sectionInset = UIEdgeInsets(top: 0,left: 0,bottom: 0,right: 0)
        layout.minimumLineSpacing = 1
        layout.minimumInteritemSpacing = 0.5
        layout.scrollDirection = .vertical
        return layout
    }()
    lazy var layout2:UICollectionViewFlowLayout = {
        let layout = UICollectionViewFlowLayout()
        layout.footerReferenceSize = CGSize(width: 0,height: 0)
        layout.sectionInset = UIEdgeInsets(top: 0,left: 0,bottom: 0,right: 0)
        layout.minimumLineSpacing = 1
        layout.minimumInteritemSpacing = 0.5
        layout.scrollDirection = .vertical
        return layout
    }()
    lazy var topHeader:ZyaSmallHeader = {
        let v = ZyaSmallHeader()
        v.titleLabel.text = "数据录入"
        return v
    }()
 
    lazy var bottomHeader:ZyaSmallHeader = {
        let v = ZyaSmallHeader()
        v.titleLabel.text = "报表查询"
        return v
    }()
    lazy var topBg:UIView = {
        let v = UIView()
        v.backgroundColor = .white
         return v
    }()
   
    
    lazy var topTable:UITableView = {
        let v = UITableView()
        v.backgroundColor = UIColor.white
        
        v.separatorStyle = .none
        return v
    }()
    lazy var topSepLine:UIView = {
        let v = UIView()
        v.backgroundColor = UIColor(kshex: "#CACEE1")
        return v
    }()
    
    lazy var bottomBg:UIView = {
        let v = UIView()
        v.backgroundColor = .white
         return v
    }()
    
    lazy var bottomTable:UITableView = {
        let v = UITableView()
        v.backgroundColor = UIColor.white
      
        v.separatorStyle = .none
        return v
    }()
    lazy var bottomSepLine:UIView = {
        let v = UIView()
        v.backgroundColor = UIColor(kshex: "#CACEE1")
        return v
    }()
    var clloHAll:CGFloat = 0
    var contentH:CGFloat = 0
    var headerH:CGFloat = 32
    var headertopMargin:CGFloat = 8

    var tableBottomMargin:CGFloat = 5
    var tableWW:CGFloat = 83
    
    
    var topTitles:[String] = []
    var topIndex = 0
    var bottomIndex = 0
    
    var reportArray = [DyncReportModel]() {
        didSet {
            if PlatformManager.shared.platform == .zhuYouAn {
                if reportArray.count == 0 {
                    topBg.snp.updateConstraints { make in
                        make.height.equalTo(contentH + (headertopMargin + headerH + contentH))
                    }
                } else {
                    topBg.snp.updateConstraints { make in
                        make.height.equalTo(contentH)
                    }
                }
                
                bottomHeader.isHidden = reportArray.count == 0
                bottomBg.isHidden = reportArray.count == 0
                
                DispatchQueue.main.async {
                    self.topBg.layoutIfNeeded()
                    
                    self.topIndex = 0
                    self.topTable.reloadData()
                    
                    self.bottomIndex = 0
                    self.bottomTable.reloadData()
                }
            }
        }
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        topTitles = getToptitles()
        
        topTable.delegate = self
        topTable.dataSource = self
        bottomTable.delegate = self
        bottomTable.dataSource = self
    }
    // 子类实现
    func getToptitles() -> [String] {
        return []
    }
    
    func setUpUI(){
        
  
        // 12 是给底部留一点间隙
        clloHAll = KSGlobal.screenH  - getTopH() - DQTitleHeight -  TabbarHeight - 12
        contentH = (clloHAll - headerH * 2 - headertopMargin * 3) / 2
        
        self.view.backgroundColor = UIColor(kshex: "eef3f9")
        
        // 上半部分
        self.view.addSubview(topHeader)
        topHeader.snp.makeConstraints { make in
            make.left.right.equalTo(self.view)
            make.top.equalTo(self.view).offset(headertopMargin)

            make.height.equalTo(headerH)
        }
      
        
        self.view.addSubview(topBg)
        topBg.snp.makeConstraints { make in
            make.left.equalTo(self.view).offset(8)
            make.right.equalTo(self.view).offset(-8)
            make.top.equalTo(topHeader.snp.bottom)
            make.height.equalTo(contentH)
        }
        
        let t_left_r = CornerView(width: 8, outColor: Theme.commonBg, innerColor: .white, type: .leftBottom)
        self.view.addSubview(t_left_r)
        t_left_r.snp.makeConstraints { make in
            make.left.bottom.equalTo(topBg)
             make.width.height.equalTo(8)
        }
        let t_right_r = CornerView(width: 8, outColor: Theme.commonBg, innerColor: .white, type: .rightBottom)
        self.view.addSubview(t_right_r)
        t_right_r.snp.makeConstraints { make in
            make.right.bottom.equalTo(topBg)
             make.width.height.equalTo(8)
        }
        
        
        
        
        topBg.addSubview(topTable)
        topTable.snp.makeConstraints { make in
            make.left.equalTo(topBg)
            make.bottom.equalTo(topBg).offset(-tableBottomMargin)

            
            make.top.equalTo(topBg)
            make.width.equalTo(tableWW)
        }
        topBg.addSubview(topSepLine)
        topSepLine.snp.makeConstraints { make in
            make.left.equalTo(topTable.snp.right)
            make.centerY.equalTo(topTable)
            make.height.equalTo(topTable).multipliedBy(0.93)
            make.width.equalTo(2)
        }
        self.view.addSubview(topCollection)
        topCollection.snp.makeConstraints { make in
            make.left.equalTo(topSepLine.snp.right)
            make.right.equalTo(topBg)
            
            if PlatformManager.shared.platform == .zhuYouAn {
                make.top.equalTo(topHeader).offset(10)
                make.bottom.equalTo(topBg)
            } else {
                make.centerY.equalTo(topSepLine)
                make.height.equalTo(topSepLine)
            }
        }
        
        // 下半部分
        self.view.addSubview(bottomHeader)
        bottomHeader.snp.makeConstraints { make in
            make.left.right.equalTo(self.view)
            make.top.equalTo(topBg.snp.bottom).offset(headertopMargin)
            make.height.equalTo(headerH)
             
        }
    
        
        self.view.addSubview(bottomBg)
        bottomBg.snp.makeConstraints { make in
            make.left.equalTo(self.view).offset(8)
            make.right.equalTo(self.view).offset(-8)
            make.top.equalTo(bottomHeader.snp.bottom)
            make.height.equalTo(contentH)
        }
        
        
        let b_left_r = CornerView(width: 8, outColor: Theme.commonBg, innerColor: .white, type: .leftBottom)
        self.view.addSubview(b_left_r)
        b_left_r.snp.makeConstraints { make in
            make.left.bottom.equalTo(bottomBg)
             make.width.height.equalTo(8)
        }
        let b_right_r = CornerView(width: 8, outColor: Theme.commonBg, innerColor: .white, type: .rightBottom)
        self.view.addSubview(b_right_r)
        b_right_r.snp.makeConstraints { make in
            make.right.bottom.equalTo(bottomBg)
             make.width.height.equalTo(8)
        }
        
        
        bottomBg.addSubview(bottomTable)
        bottomTable.snp.makeConstraints { make in
            make.left.equalTo(bottomBg)
            make.bottom.equalTo(bottomBg).offset(-tableBottomMargin)
          
            make.top.equalTo(bottomBg)
            make.width.equalTo(tableWW)
        }
        bottomBg.addSubview(bottomSepLine)
        bottomSepLine.snp.makeConstraints { make in
            make.left.equalTo(bottomTable.snp.right)
            make.centerY.equalTo(bottomTable)
            make.height.equalTo(bottomTable).multipliedBy(0.93)
            make.width.equalTo(2)
        }
     
       
        
        bottomBg.addSubview(bottomCollection)
        bottomCollection.snp.makeConstraints { make in
            make.left.equalTo(bottomSepLine.snp.right)
            make.right.equalTo(bottomBg)
            
            if PlatformManager.shared.platform == .zhuYouAn {
                make.top.equalTo(bottomHeader).offset(10)
                make.bottom.equalTo(bottomBg)
            } else {
                make.centerY.equalTo(bottomSepLine)
                make.height.equalTo(bottomSepLine)
            }
        }
        
    }
    // 子类实现
    func topItemConfig(_ index:Int) {
        
    }
    // 子类实现
    func bottItemConfig(_ index:Int) {
    }
    func getReportArr(bigId:String) {
        getDyncReport(newFlag: true, bigId: bigId) { arr in
            
            if PlatformManager.shared.platform == .zhuYouAn {
                self.reportArray = arr.filter({ $0.reportList.count > 0 })
            } else {
                self.reportArray = arr
            }
            
            self.bottomIndex = 0
            self.bottItemConfig(self.bottomIndex)
        }
    }
}
 
extension YZBaseVC: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if objectEquateable(object1: tableView, object2: topTable)  {
            return topTitles.count
        } else {
            return  self.reportArray.count
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return (contentH - tableBottomMargin)/5
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        guard let cell = tableView.dequeueReusableCell(withIdentifier: BoarSuperTableCell.identifier, for: indexPath) as? BoarSuperTableCell else {
            fatalError()
        }
        if  objectEquateable(object1: tableView, object2: topTable) {
            let titleColor = self.topIndex == indexPath.row ? UIColor.white : UIColor(kshex: "#CACEE1")
            
            cell.left1.setTitle(topTitles[indexPath.row], for: .normal)
            cell.left1.setTitleColor(titleColor, for: .normal)

            cell.bg.backgroundColor = self.topIndex == indexPath.row ? Theme.primaryColor() : .clear
            
        } else {
            let titleColor = self.bottomIndex == indexPath.row ? UIColor.white : UIColor(kshex: "#CACEE1")

            let titleS = self.reportArray[indexPath.row].item_nm.unwrap
            cell.left1.setTitle(titleS, for: .normal)
            cell.left1.setTitleColor(titleColor, for: .normal)

            cell.bg.backgroundColor = self.bottomIndex == indexPath.row ? Theme.primaryColor() : .clear
            
        }
        
        cell.textLabel?.numberOfLines = 0
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if  objectEquateable(object1: tableView, object2: topTable)  {
            self.topIndex = indexPath.row
            self.topItemConfig(self.topIndex)
        } else {
            self.bottomIndex = indexPath.row
            self.bottItemConfig(self.bottomIndex)
        }
    }
}


func showRepList(bAlertV: FollowAlertV, thisVC: UIViewController, bottomCollection: UICollectionView, repOne: ReportList, indexPath: IndexPath, didRemove: @escaping (() -> ())) {
    let item = bottomCollection.cellForItem(at: indexPath)
    guard item.isSome else {
        return
    }
    let itemXY = CGPoint(x: item!.ks_x, y: item!.ks_y)
    let itemXYNew = bottomCollection.convert(itemXY, to: UIApplication.shared.keyWindow!)
    let adjustOffset: CGFloat = PlatformManager.shared.platform == .zhuYouAn ? 10 : 0
    let loukongC = CGRect(x: itemXYNew.x, y: itemXYNew.y - adjustOffset, width: item!.ks_width, height: item!.ks_height + adjustOffset)
    // 有下一级，弹出选择
    if let smList = repOne.smallList {
        
        var tIArr = [MenuItem]()
        for i in 0..<smList.count {
            let oneTpX = smList[i]
            let onex =  MenuItem(resId: "", title: oneTpX.report_name.unwrap, imgStr: "",imgUrl: configURLOK(latter: oneTpX.z_pic_url.unwrap)) { parent in
                if checkPlatform(type: .zhuYouAn) {
                    go2ChartForWeb_zhuok(url: USERINFO.reportUrl.unwrap + USERINFO.reportPath.unwrap,path: oneTpX.report_url.unwrap, title: oneTpX.report_name.unwrap, parameters: ["ps_zc_id":USERINFO.zOrgId.unwrap, "ps_staff_id":USERINFO.id.unwrap,"session":Session_Key], currentVC: thisVC)
                } else {
                    go2ChartForWeb_zhuok(url: USERINFO.reportUrl.unwrap + USERINFO.picPath.unwrap,path: oneTpX.report_url.unwrap, title: oneTpX.report_name.unwrap, parameters: ["ps_zc_id":USERINFO.zOrgId.unwrap, "ps_staff_id":USERINFO.id.unwrap,"session":Session_Key], currentVC: thisVC)
                }
            }
            tIArr.append(onex)
        }
        
        bAlertV.setDataArrAndAlert(alertDirectory:repOne.report_name.unwrap,superVC: thisVC, arr: tIArr, loukong: loukongC, derection: .top)  {
            
            didRemove()
            
//            self.bottomCollection.reloadData()
        }
        
        
    } else {
        if checkPlatform(type: .zhuYouAn) {
            go2ChartForWeb_zhuok(url: USERINFO.reportUrl.unwrap + USERINFO.reportPath.unwrap,path: repOne.report_url.unwrap, title: repOne.report_name.unwrap, parameters: ["ps_zc_id":USERINFO.zOrgId.unwrap, "ps_staff_id":USERINFO.id.unwrap,"session":Session_Key], currentVC: thisVC)
        } else {
            go2ChartForWeb_zhuok(url: USERINFO.reportUrl.unwrap + USERINFO.picPath.unwrap,path: repOne.report_url.unwrap, title: repOne.report_name.unwrap, parameters: ["ps_zc_id":USERINFO.zOrgId.unwrap, "ps_staff_id":USERINFO.id.unwrap,"session":Session_Key], currentVC: thisVC)
        }
    }
}
